<?php
/**
 * 功能：文件上传类
 * 版本：1.2.0
 */
Class Helper_Upload
{
	public $thumb = array();//array(array("width"=>"144","height"=>"162"));
/*	$markwords-水印文字, 
	$markimage-水印图片, 
	$dstW-图片保存宽度, 
	$dstH-图片保存高度, 
	$rate-图片保存品质*/
	public $ThumbWidth;
	public $ThumbHeight;
	public $ThumbRate;
	public $ThumbMarkImage;
	public $ThumbMarkWords;
	private $surfix_name;
	
	function __construct()
	{
		$this->ThumbWidth = 100;
		$this->ThumbHeight = 100;
		$this->ThumbRate = 100;
		$this->ThumbMarkImage = null;
		$this->ThumbMarkWords = null;
		$this->surfix_name = "";
	}
	/**
	 * 取得网站的绝对根目录
	 * @return 网站的绝对根目录字符串
	 */
	function RetrieveTruePath()
	{
		$path = dirname(dirname(__FILE__));//$_SERVER["DOCUMENT_ROOT"].'/';
		//die(var_dump($path));
		//$path = str_replace("helper", "", $path);
		//$path = str_replace("\\", DIRECTORY_SEPARATOR, $path);
		return $path;
	}
	
	/**
	 * 文件上传
	 * 
	 */
	function UploadFiles($savedir, $filefield="", $file_type_name="", $keep_filename=false, $exist_name="")
	{
		$savedir = trim(trim($savedir, '/'), '\\');
		if( defined('PATH_MEDIA') ){
			$root_path = PATH_MEDIA;
		} else {
			$root_path = $this->RetrieveTruePath();
		}
		
		$savedir = SITE_CURRENT.DIRECTORY_SEPARATOR.$savedir;
		
		//die(var_dump($root_path));
		$arrfiles = Array();
		$file_type = array();
		$i = 0;
		//die(var_dump($_FILES));
	//	die(var_dump($this->thumb));
		//注意变小写
		if($file_type_name == ""){
			$file_type_name = "image";
//			$file_size = FILE_SIZE_IMAGE;
//			$filetype = explode("|",FILE_ALLOWED_IMAGE);
		}
//		
//		else if($file_type_name == "archive"){
//			$file_type_name = "archive";
//			$file_size = FILE_SIZE_ARCHIVE;
//			$filetype = explode("|",FILE_ALLOWED_ARCHIVE);
//		}
//		
		$file_type_name = strtoupper($file_type_name);
		$file_size = 0;
		$filetype = array();
		
		eval('$file_size = FILE_SIZE_'.$file_type_name.';');
		eval('$filetype = explode("|", FILE_ALLOWED_'.$file_type_name.');');
	//	eval('$file_append = FILE_APPEND_'.$file_type_name.';');
		
		
		//die(var_dump($root_path.$savedir));
		//1，上传的文件超过了 php.ini 中 upload_max_filesize 
		//处理目录，创建不存在的目录
		$this->createFolder($root_path.$savedir);
		//die($root_path.$savedir);
	//	die('aaaaaaaaaaaa');
		//die(var_dump($_FILES));
		foreach ($_FILES as $array_key=>$array_val)
		{
			if(!is_array($array_val["name"])){
				$array_val["name"]= array($array_val["name"]);
				$array_val["type"]= array($array_val["type"]);
				$array_val["tmp_name"]= array($array_val["tmp_name"]);
				$array_val["error"]= array($array_val["error"]);
				$array_val["size"]= array($array_val["size"]);
			}
			//die('aaaaa');
			$array_file_count = count($array_val["name"]);
			//die(var_dump($array_file_count));
			for( $array_file_step=0; $array_file_step<$array_file_count; $array_file_step++ )
			{
				if((is_array($filefield) && !in_array($array_key,$filefield))
				|| ( !is_array($filefield) && $filefield !="" && $array_key!=$filefield )
				|| ($array_val['name'][$array_file_step] == ""))
				{
					continue;
				}
				//die("aaaaa");
				//print_r(stripslashes($array_val['tmp_name'][$array_file_step]));
				//die();
				//stripslashes
				if(@is_uploaded_file( $array_val['tmp_name'][$array_file_step]))
				{
					$filename = $array_val['name'][$array_file_step];
					$extname = end(explode('.', $filename));
					
					$upload_filetype = $array_val['type'][$array_file_step];
					$oldname = end(explode(DIRECTORY_SEPARATOR, $filename));
					//die($oldname);
					//stripslashes
					$filesize = filesize($array_val['tmp_name'][$array_file_step]);
					//die($filesize.']');
					//检查是否是允许的文件类型
					//if($filetype[0] != "*" && !preg_match(("/(".implode("|",$filetype).")$/i"),$filename))
					//{
					//	WriteErrorMessage("File is not allowed to be uploaded.<br>Allowed files: ".implode(", ", $filetype));
					//}
					
					//检查上传文件的大小
					//if(  $file_size != 0 && $filesize > $file_size)
					//{
					//	WriteErrorMessage("File is too large, not allow to be uploaded.<br>Allowed size: ".$file_size/1024 ."KB");
					//}
					
					if( !$keep_filename )
					{
						if( $exist_name <> "" )
						{
							$filename = $exist_name;
							$savefile = $savedir.DIRECTORY_SEPARATOR.$exist_name;
							$exist_name = "";//使用过就清空
						} else {
							$RandomNameCount = 0;
							do
							{
								$filename=$this->GetRandomFile($filename);
								$RandomNameCount++;
								$savefile = $savedir.DIRECTORY_SEPARATOR.$filename;
							}while(file_exists($root_path.$savefile) || $RandomNameCount>=5 );
							
							if($RandomNameCount>=5){
								break;
							}
						}
					} else {
						$savefile = $savedir.DIRECTORY_SEPARATOR.$filename;
					}
					//die('['.$savefile.']');
					//die(iconv_get_encoding("all"));
					//die($root_path.$savefile.$this->surfix_name);
					//echo $upload_filetype;
					$file_type = split("/", $upload_filetype);
					
					if( $file_type[0] != 'image') {
						$savefile = $savefile.$this->surfix_name;
					}
					//die(stripslashes($array_val['tmp_name'][$array_file_step]).']'.$savefile);
					//die($root_path.$savefile);
					$result = @move_uploaded_file( $array_val['tmp_name'][$array_file_step], $root_path.$savefile);
					//die(var_dump($result));
					//die($file_type_name);
					
					if($result && $file_type[0] == 'image' ){
						//die('aaaaa');
						$arr = getimagesize($root_path.$savefile);
						//die(var_dump($arr));
						$strarr = explode("\"",$arr[3]);
						$iWidth = $strarr[1];
						$iHeight = $strarr[3];
						foreach ($this->thumb as $v){
							$this->ThumbWidth = $v["width"];
							$this->ThumbHeight = $v["height"];
							if( $v["name"] == ""){
								$v["name"] = "_thumbnail";
							}
							
							$this->makethumb($root_path.$savefile, str_replace(".".$extname, $v["name"].".".$extname,$root_path.$savefile));
						}
					}
					//die($upload_filetype);
					//die($root_path.$savefile);
					
					if($result) {
						@chmod($root_path.$savefile, 0664);
						//$oldname = iconv("utf-8", "utf-8", $oldname);
						$arrfiles[$i] = array('file'=>"/".str_replace("\\", "/", $savefile),
								'name'=>$oldname,
								'type'=>$file_type[0],
								'size'=>$filesize,
								'control'=>$array_key,
								'width'=>$iWidth,
								'height'=>$iHeight);
					    $i++;
					}
				}
			}
		}
		return $arrfiles;
	}
	
//	/**
//	 * 生成上传文件所在的目录
//	 * @param 绝对目录
//	 * @param $index
//	 * @return 创建是否成功的bool值
//	 */
//	function makeDirectory($savedir)
//	{
////		die(var_dump($savedir));
////		$savedir = str_replace("\\", DIRECTORY_SEPARATOR, $savedir);
////		die(var_dump($savedir));
////		$savedir = str_replace("//", DIRECTORY_SEPARATOR, $savedir);
////		DIE(var_dump(DIRECTORY_SEPARATOR));
//		$arraydir = explode(DIRECTORY_SEPARATOR, $savedir);
//		die(var_dump($arraydir));
//		for($i=0; $i<count($arraydir); $i++){
//			if( $arraydir[$i] == "."
//				|| $arraydir[$i] == ".."
//				|| $arraydir[$i] == ""
//				|| count(explode(":", $arraydir[$i])>1)){
//				$parentdir .= $arraydir[$i]."/";
//			} else {
//				$parentdir .= $arraydir[$i].'/';
//			}
//			if(!file_exists($parentdir)) {
//				mkdir(iconv("UTF-8",charset,$parentdir),0775,true);
//				chmod(iconv("UTF-8",charset,$parentdir),0775);
//		    }
//		}
//		
//	    return true;
//	}
//	
	public function createFolder($path)
	{
		$path = rtrim($path,"\\/");
		if (!file_exists($path)) {
			if (!file_exists(dirname($path))) {
				$this->createFolder(dirname($path));
			} else {
				mkdir(dirname($path, 0777));
			}
			
			if( mkdir($path, 0777) == false ){
				
				die($path."Path created failed!");
			} else {
				//die('aaaa'); 
			}
		}
	}
	
	/**
	 * 生成缩略图（文字或图片水印）
	 * @param 源图片文件名
	 * @param 目标图片文件名
	 * @return 无
	 */
	private function makethumb($srcFile, $dstFile) 
	{
		global $system;
		$data = GetImageSize($srcFile); 
		switch($data[2]) 
		{ 
			case 1: 
				$im=@ImageCreateFromGIF($srcFile); 
				break; 
			case 2: 
				$im=@ImageCreateFromJPEG($srcFile); 
				break; 
			case 3: 
				$im=@ImageCreateFromPNG($srcFile); 
				break; 
		} 
		if(!$im) return False; 
		$srcW=ImageSX($im); 
		$srcH=ImageSY($im); 
		$dstX=0; 
		$dstY=0; 
		if ($srcW*$this->ThumbHeight>$srcH*$this->ThumbWidth) 
		{ 
			$fdstH = round($srcH*$this->ThumbWidth/$srcW); 
			$dstY = floor(($this->ThumbHeight-$fdstH)/2); 
			$fdstW = $this->ThumbWidth; 
		} else { 
			$fdstW = round($srcW*$this->ThumbHeight/$srcH); 
			$dstX = floor(($this->ThumbWidth-$fdstW)/2); 
			$fdstH = $this->ThumbHeight; 
		} 
		$ni=ImageCreateTrueColor($this->ThumbWidth,$this->ThumbHeight); 
		$dstX=($dstX<0)?0:$dstX; 
		$dstY=($dstX<0)?0:$dstY; 
		$dstX=($dstX>($this->ThumbWidth/2))?floor($this->ThumbWidth/2):$dstX; 
		$dstY=($dstY>($this->ThumbHeight/2))?floor($this->ThumbHeight/s):$dstY; 
		$white = ImageColorAllocate($ni,255,255,255); 
		$black = ImageColorAllocate($ni,0,0,0); 
		imagefilledrectangle($ni,0,0,$this->ThumbWidth,$this->ThumbHeight,$white);// 填充背景色 
		ImageCopyResized($ni,$im,$dstX,$dstY,0,0,$fdstW,$fdstH,$srcW,$srcH); 
		if($this->ThumbMarkWords!=null) 
		{ 
			if(charset!= ""){
				$this->ThumbMarkWords=iconv(charset,"UTF-8",$this->ThumbMarkWords);
			} 
			//转换文字编码 
			ImageTTFText($ni,20,30,450,560,$black,"simhei.ttf",$this->ThumbMarkWords); //写入文字水印 
			//参数依次为，文字大小|偏转度|横坐标|纵坐标|文字颜色|文字类型|文字内容 
		} 
		elseif($this->ThumbMarkImage!=null) 
		{ 
			$wimage_data = GetImageSize($this->ThumbMarkImage); 
			switch($wimage_data[2]) 
			{ 
				case 1: 
					$wimage=@ImageCreateFromGIF($this->ThumbMarkImage); 
					break; 
				case 2: 
					$wimage=@ImageCreateFromJPEG($this->ThumbMarkImage); 
					break; 
				case 3: 
					$wimage=@ImageCreateFromPNG($this->ThumbMarkImage); 
					break; 
			} 
			imagecopy($ni,$wimage,500,560,0,0,88,31); //写入图片水印,水印图片大小默认为88*31 
			imagedestroy($wimage); 
		}
		
		ImageJpeg($ni,$dstFile,100); 
		//ImageJpeg($ni,$srcFile,$this->ThumbRate); 
		imagedestroy($im); 
		imagedestroy($ni); 
	}

	/**
	 * 取得随机文件名，日期加下划线加八位随机码
	 * @param 原文件名,目的是取扩展名
	 * @return 新文件名
	 */
	private function GetRandomFile($filename)
	{
		return date('Ymd').'_'.soyia_string_random(8) . '.' . end(explode('.', $filename));
	}
	
	public function checkSpaceSize($type=0)
	{
		global $system, $db, $security;
		$language_nospace = setLanuageText(array("No more space to allow upload, please remove unused file or apply for valued member!", "空间不足，请删除未用的空间或申请增值会员！"));
		$language_spacereserved = setLanuageText(array("#space_kb#KB / #space_mb#MB available", "剩余空间 #space_kb#KB / #space_mb#MB"));
		
		//1024*1024*100
		//$file_size_allocation = 1048576000;
		$condition = " and Member_id='".$security->id."'";
		$sql = "Select ifnull(sum(iSize), 0) as iSizes from ".DATABASE_PREFIX."memberfile where 1=1 " .$condition;
		//die($sql);
		$result = $this->database->query( $sql);
		//var_dump($result);
		$file_used_byte = $result["iSizes"];
		$file_reserved_kb = intval((FILE_SIZE_SPACE - $file_used_byte)/1024);
		$file_reserved_mb = intval((FILE_SIZE_SPACE - $file_used_byte)/1024/1024);
		$file_reserved_tip = str_replace("#space_mb#", $file_reserved_mb, str_replace("#space_kb#", $file_reserved_kb, $language_spacereserved));
		if($file_reserved_kb <= 0)
		{
			if( $type == 0){
				WriteErrorMessage( $language_nospace );
			}
		}
		
		return array(
			"used"=>array("byte"=>$file_used_byte),
			"unused"=>array(
				"byte"	=> FILE_SIZE_SPACE,
				"kb"	=> $file_reserved_kb,
				"mb"	=> $file_reserved_mb),
			"message"=>array("status"=>$file_reserved_tip));
	}
}
?>